﻿package chenji.moreitemfunapi.item;

import java.util.HashMap;

import org.bukkit.inventory.ItemStack;

import com.google.common.collect.Maps;

import chenji.itemeditor.util.NMSItem;
import chenji.moreitemfunapi.MifAPI;
import chenji.moreitemfunapi.plugin.MifPlugin;

public class MifItemManager {
	private HashMap<String, MifItem> allItems = Maps.newHashMap();

	public boolean isMifItem(ItemStack item) {
		NMSItem nmsitem = NMSItem.getItem(item);
		return nmsitem.getTag().get("mif.identifyname") == null;
	}

	public boolean isLoaded(String name) {
		return this.allItems.containsKey(name);
	}

	public MifItem loadMifItem(ItemStack item, String name) {
		if (this.isLoaded(name)) {
			return null;
		}
		MifItem mifitem = new MifItem(name, item);
		this.allItems.put(name, mifitem);
		return mifitem;
	}

	public boolean loadMifItem(MifItem item, String plne) {
		if (this.isLoaded(item.getIdentifyname())) {
			return false;
		}
		if (item.isEnabletextures()) {
			MifAPI.getTexturesManager().registerItem(item);
		}
		this.allItems.put(item.getIdentifyname(), item);
		return true;
	}

	public MifItem getMifItem(String name) {
		return this.allItems.get(name);
	}

	public void updatemifitem(MifItem item) {
		this.allItems.put(item.getIdentifyname(), item);
	}

	public void registerItem(MifPlugin instance, MifItem item) {
		item.setPluginName(instance.getName());
		if (item.getIdentifyname().startsWith(instance.getName())) {
			boolean isSuccess = this.loadMifItem(item, instance.getName());
			if (!isSuccess) {
				MifAPI.getMLogger().warning("加载插件" + instance.getName() + "的物品" + item.getIdentifyname() + "时发生异常：物品名称被占用或被重复注册");
			}
		} else {
			MifAPI.getMLogger().warning("加载插件" + instance.getName() + "的物品" + item.getIdentifyname() + "时发生异常：物品识别名必须以插件名_开头。");
		}
	}

	public HashMap<String, MifItem> getAllMifItem() {
		return this.allItems;
	}

	public void closeTexture(String name, boolean keep) {
		if (this.allItems.containsKey(name)) {
			MifItem item = this.allItems.get(name);
			item.setEnableTextures(false);
			MifAPI.getTexturesManager().closeTexture(name, keep);
		}
	}

	public void openTexture(String name) {
		if (this.allItems.containsKey(name)) {
			MifItem item = this.allItems.get(name);
			item.setEnableTextures(true);
			MifAPI.getTexturesManager().registerItem(item);
		}
	}

}
